import 'package:flutter/material.dart';
import 'package:flutter_ai/deepseek/x_message.dart';
import 'package:flutter_ai/deepseek/x_model.dart';
import 'package:flutter_ai/deepseek/x_deepseek.dart';
import 'package:flutter_ai/utils/x_toast.dart';
import 'package:flutter_quill/flutter_quill.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      builder: XToast.initToast(),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    super.key,
  });

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  final XDeepSeek xDeepSeek = XDeepSeek(apiKeys: 'sk-b0d31602140f437aa1e63097714c3042');
  final quillController = QuillController.basic();
  final ValueNotifier<String> _chatResponseNotifier = ValueNotifier('');

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 初始化 Toast 配置
      XToast.setToastConfig();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('Deepseek'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                /// 文本输入框
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
                  decoration: BoxDecoration(
                    color: const Color(0xfff3f3f3),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: QuillEditor.basic(
                    configurations: QuillEditorConfigurations(
                      controller: quillController,
                      checkBoxReadOnly: false,
                      minHeight: 80,
                      placeholder: '请输入内容',
                      padding: const EdgeInsets.all(10),
                    ),
                  ),
                ),

                /// deepseek响应文本
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: ValueListenableBuilder(
                    valueListenable: _chatResponseNotifier,
                    builder: (context, value, child) => Text(
                      value,
                      style: const TextStyle(
                        fontSize: 16,
                        color: Colors.black,
                      ),
                    ),
                  ),
                ),
              ],
            ),

            /// 点击补全对话发送
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 20),
              child: TextButton(
                onPressed: () => _sendChat(),
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.blue),
                  minimumSize: MaterialStateProperty.all(
                    Size(MediaQuery.of(context).size.width - 40, 40),
                  ),
                ),
                child: const Text(
                  '发送',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 22,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 发送chat
  void _sendChat() async {
    if (quillController.document.toPlainText().isEmpty) {
      XToast.showError('请输入内容');
      return;
    }

    _chatResponseNotifier.value = '加载中...';
    try {
      final data = await xDeepSeek.createChatCompletion(
        messages: [
          XMessage(
            role: 'user',
            content: quillController.document.toPlainText(),
          ),
        ],
        model: XChatModel.chat,
      );
      if (data != null) {
        _chatResponseNotifier.value = data.choices.last.message?.content ?? '喔！Deepseek没回答上来。';
      } else {
        _chatResponseNotifier.value = '喔！Deepseek没回答上来。';
      }
    } on XException catch (e) {
      XToast.showError(e.message);
      _chatResponseNotifier.value = e.message;
    }
  }
}
